package com.ultrasoft.farmasoft.web;

import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.google.gson.JsonArray;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.ultrasoft.farmasoft.domain.Pharmacy;
import com.ultrasoft.farmasoft.domain.Pharmacystock;
import com.ultrasoft.farmasoft.domain.Stock;
import com.ultrasoft.farmasoft.domain.Userpharmacy;
import com.ultrasoft.farmasoft.service.StockService;
import com.ultrasoft.farmasoft.util.UtilCommon;
import com.ultrasoft.farmasoft.util.UtilConverter;


@Controller
@SessionAttributes({"s_UserPharmacy"}) 
@RequestMapping(value="/Stock")
public class AdminStockController {
	private final StockService stockService;
	private HttpSession session;
	private Userpharmacy s_UserPharmacy;
	private int s_userId;
	private int s_pharmacyId;
	
	private String stockId_ = "_stockId";
	private String userId_	= "_userId";
	
	@Autowired
	public AdminStockController(StockService stockService) {
		this.stockService = stockService;
	}
	private boolean sessionControl(HttpServletRequest request){
		boolean res = false;
		session = request.getSession(true);
		if(session.getAttribute("s_UserPharmacy") != null){
			s_UserPharmacy 	= (Userpharmacy)session.getAttribute("s_UserPharmacy");
			s_userId 		= s_UserPharmacy.getUser().getUserId();
			s_pharmacyId 	= s_UserPharmacy.getPharmacy().getPharmacyId();
			res = true;
		}
		return res;
	}
	private String redirectStock(HttpServletRequest request){
		if(!sessionControl(request))
			return "redirect:/index"; 
		else
			return "redirect:/adminStock?"+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_); 
	}	
	private String handleRedirectStock(HttpServletRequest request,String headMain) {
    	try {
    		return "redirect:/"+headMain+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_); 
		} catch (Exception e) {
			return redirectStock(request);
		}
    }
	
	@RequestMapping(value="/adminStock", method=RequestMethod.GET)
	public String handleRequestAdminStock(HttpServletRequest request, Model model) throws ServletException {
		return UtilCommon.fAdministration_Stock+"mainStockAdministration";
	}
	@RequestMapping(value="/dataStock", method=RequestMethod.GET)
	public String handleRequestDataStock(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){
			model.addAttribute("listUserPharmacy",stockService.getListUserPharmacy(s_pharmacyId, true));
			//model.addAttribute("listPharmacyStock",stockService.getListPharmacyStock());
			model.addAttribute("listPharmacyStock",stockService.getListPharmacyStockByPharmacyId(s_pharmacyId));
			return UtilCommon.fAdministration_Stock_Data+"dataStock";
		}else
			return redirectStock(request);
	}
	@RequestMapping(value = "/ajaxDataStockAddEdit", method = RequestMethod.POST)
	public @ResponseBody String handleRequestajAxGiveLowOrHighToPharmacy(@RequestParam Integer action,@RequestParam String name, @RequestParam String address,@RequestParam String phone,@RequestParam String remark,HttpServletRequest request){
		String res = "";
		if(this.sessionControl(request)){
			int tempStock = UtilConverter.converterStringToInteger(request,stockId_);
			if(action == 0 && tempStock >= 0){
				Pharmacystock findPharmacyStock = stockService.searchPharmacyStockByPharmacyIdByStockId(s_pharmacyId,tempStock);
				if(findPharmacyStock != null)
					return "-2";
				
				if(tempStock != 0){
					Stock s = stockService.searchStockByStockId(tempStock);
					s.setName(name);
					s.setAddress(address);
					s.setPhone(phone);
					s.setRemark(remark);
					Pharmacy p = stockService.searchPharmacyByPharmacyId(s_pharmacyId);
					stockService.addPharmacyStock(new Pharmacystock(p, s, true));
				}else{
					if(tempStock == 0){
						Userpharmacy userPharmacy= stockService.searchUserPharmacyByPharmacyIdByUserId(s_pharmacyId,UtilConverter.converterStringToInteger(request,userId_));
						Stock s = new Stock(null, name);
						s.setAddress(address);
						s.setPhone(phone);
						s.setRemark(remark);
						s.setUserpharmacy(userPharmacy);
						stockService.addStock(s);
						Pharmacy p = stockService.searchPharmacyByPharmacyId(s_pharmacyId);
						stockService.addPharmacyStock(new Pharmacystock(p, s, false));
					}
				}				
				res = "0";
			}else{
				tempStock = UtilConverter.converterStringToInteger(request,"_stockIdTemp");
				if(action == 1 && tempStock >= 0){
					Pharmacystock findPharmacyStock = stockService.searchPharmacyStockByPharmacyIdByStockId(s_pharmacyId,tempStock);
					if(findPharmacyStock != null){
						Userpharmacy userPharmacy= stockService.searchUserPharmacyByPharmacyIdByUserId(s_pharmacyId,UtilConverter.converterStringToInteger(request,userId_));
						Stock s = stockService.searchStockByStockId(tempStock);
						s.setName(name);
						s.setAddress(address);
						s.setPhone(phone);
						s.setRemark(remark);
						s.setUserpharmacy(userPharmacy);
						stockService.updateStock(s);
						res = "1";
					}					
				}
			}
			return res;
		}else
			return redirectStock(request);
    }
	
	//remove Stock
	@RequestMapping(value = "/ajaxDataStockRemove", method = RequestMethod.GET)
	public @ResponseBody String handleRequestRemoveStook(@RequestParam Integer stockId,@RequestParam String name, HttpServletRequest request){
		System.out.println(request.getParameterMap());
		
		stockService.removeStock(stockService.searchStockByStockId(stockId));
		return "El Almacen "+name+" se Elimino correctamente!!!";
	}
	
	@RequestMapping(value = "/ajaxDataStockSelectedPharmacyStock", method = RequestMethod.GET)
   	protected @ResponseBody String handleRequestAjaxDataStockGetObjectPharmacyStock(@RequestParam Integer pharmacyId,@RequestParam Integer stockId,HttpServletRequest request)throws JsonIOException{		
		Pharmacystock pharmacyStock = stockService.searchPharmacyStockByPharmacyIdByStockId(pharmacyId, stockId);
		JsonArray groupArray = new JsonArray();
        if(pharmacyStock != null){
            JsonObject groupJSON = new JsonObject();
            groupJSON.addProperty("pharmacyId",pharmacyStock.getPharmacystockPK().getPharmacyId());
            groupJSON.addProperty("stockId",pharmacyStock.getPharmacystockPK().getStockId());
            groupJSON.addProperty("userId",(pharmacyStock.getStock().getUserpharmacy() != null) ? pharmacyStock.getStock().getUserpharmacy().getUser().getUserId()+"" : "");
            groupJSON.addProperty("name",(pharmacyStock.getStock().getName() != null) ? pharmacyStock.getStock().getName() : "");
            groupJSON.addProperty("address",(pharmacyStock.getStock().getAddress() != null) ? pharmacyStock.getStock().getAddress() : "");
            groupJSON.addProperty("phone",(pharmacyStock.getStock().getPhone() != null) ? pharmacyStock.getStock().getPhone() : "");
            groupJSON.addProperty("remark",(pharmacyStock.getStock().getRemark() != null) ? pharmacyStock.getStock().getRemark() : "");
            groupArray.add(groupJSON);
		}else{
			JsonObject groupJSON = new JsonObject();
            groupJSON.addProperty("name","");
            groupArray.add(groupJSON);
		}
    	return groupArray.toString();
    }	
	
	
	
	@RequestMapping(value="/itemStock", method=RequestMethod.GET)
	public String handleRequestItemStock(HttpServletRequest request, Model model) throws ServletException {
		return UtilCommon.fAdministration_Stock_Items+"itemStock";
	}
	
}
